<?php
/**
 * Answer
 *
 * Класс Answer осуществляет вывод на экран ответов
 * @version 1.0
 */
class View_Answer {

  public static function displayAnswer($arrAnswer, $idBestAnswer, $questionAuthorId, $isUserAdmin, $idFolder, $profileFlag = false, $return = false, $branchMinimizeLinkFlag = false, $branchMinimizeFlag = false, $issetChildren = true, $type = '', $idEssence = NULL, $rating = 0, $url="") {
    $objSession = User_Session::instance();
    if ($arrAnswer['ID_answer'] == $idBestAnswer) {
        $text = '<div class="fine_box">
      					<div class="fine_box_left">
      						<div class="fine_box_right">
      							<div class="fine_box_bottom">
      								<div class="fine_box_top_left">
      									<div class="fine_box_top_right">
      										<div class="fine_box_bottom_left">
      											<div class="fine_box_bottom_right">
                              <div class="text_comment for_fine_box">';
        if ($profileFlag)
          $text .= '<div style="float:right;"><img src="' . W_IMAGES . 'background/star_little.gif" alt="Лучший ответ" />&nbsp;&nbsp;<strong>Ответ признан лучшим</strong></div>';
      }
      else
        $text = '<div class="text_comment" idAnswer="' . $arrAnswer['ID_answer'] . '">';


        $text .= '<div class="comments_author">
    						<div class="rigt_rating_box rigt_rating_box_one_qwestion">';
        if (!$profileFlag && !$arrAnswer['deleted'] && ($questionAuthorId == $objSession->getUserId())/*&& ($questionAuthorId != $arrAnswer['ID_user']) &&*/ && is_NULL($idBestAnswer)) {
            $text .= '<div class="star">
    							  <a href="#" class="linkSelectBestAnswer" title="Выбрать этот ответ лучшим" idAnswer="' . $arrAnswer['ID_answer'] . '">
    							    <img alt="Выбрать этот ответ лучшим" src="' . W_IMAGES . 'background/bg_star.gif" height="23" width="23" />
    							  </a>
    							</div>';
        }
		if ($objSession->isLoggedIn() && !$profileFlag && !$arrAnswer['deleted']){
			$text .= View_Poll::showMark($arrAnswer['ID_answer'], 6, $arrAnswer['session_user_poll'], Poll::calculateMark($arrAnswer['marks_minus'], $arrAnswer['marks_plus']), $arrAnswer['marks_minus'], $arrAnswer['marks_plus'], true, 0, $idFolder);
		}
            $text .= '
    						</div>
									<a class="author_link" href="' . W_ABSPATH . 'user/' .  $arrAnswer['login'] . '">
										<img class="user" src="' . W_IMAGES . 'pictures/user/vs_';
						$text .= (!empty($arrAnswer['pic_path']) ? ($arrAnswer['ID_user'] . '.' . $arrAnswer['pic_path'] . '?' . rand() . '"') : ('default.gif"')) . '/>';
				$text .= '</a>';
    						$text .= '<ul class="name_autor">
    							<li><a class="color_green" href="' . W_ABSPATH . 'user/' . $arrAnswer['login'] . '/">' . $arrAnswer['login'] . '</a></li>';
    							if (!$profileFlag) $text .=  '<li><strong>[' . round($rating, 2) . '/' . $arrAnswer['folder_rating'] . ']</strong></li>';
    							$text .=  '<li>' . Service_Date::getCaseDateForUser($arrAnswer['creation']) . '</li>';
    						  if (!$profileFlag) {
    						    $text .= '
        							<li>
    							    <a href="'.$url.'#comment'.$arrAnswer['ID_comment'].'" style="background:none; color:#0089B5; padding-left:0px;">#</a>
    							    </li>';
    						  }
    						if (!$profileFlag){
					      //Проверяем, имеет ли пользователь право удалить данный ответ
					      $userCanDeleteAnswer = (($arrAnswer['ID_question_user'] == $objSession->getUserId()) || ($arrAnswer['ID_user'] == $objSession->getUserId()) || $isUserAdmin) && !$arrAnswer['deleted'] && ($arrAnswer['ID_answer'] != $idBestAnswer) && ($arrAnswer['ID_answer'] != $idBestAnswer);
						      if ($userCanDeleteAnswer){
							  		$text .= '
											<li><input type="image" value="Удалить" name="deleteComment" class="linkDeleteAnswer" idAnswer="' . $arrAnswer['ID_answer'] . '" src="' . W_ABSPATH . 'content/images/button/delete_comment_button.gif"></input></li>
											';
						  		}
    						}
    						$text .= '</ul>

    					</div>
    					<p class="answer-body' . ($arrAnswer['deleted'] ? ' delete_modetator' : NULL) . '">' .  $arrAnswer['text'] . '</p>';
            if (!$profileFlag){

				  		$id = $type . '_' . $arrAnswer['ID_comment'];
				  		if ($objSession->isLoggedIn() && $arrAnswer['deleted'] != 1){

								$text .= '<ul class="link_comment">';
		  			$url = W_ABSPATH . 'content/pages/comment/addComment.php?curEssenceId=' . $idEssence . '&type=' . $type . '&root=' . $arrAnswer['ID_comment'] . '&first_root=' . $arrAnswer['ID_first_root_comment'];
		  			$onClick = 'comment.showFormForAnswer(\'' . $id . '\', ' . $idEssence . ', \'' . $type . '\', ' . $arrAnswer['ID_comment'] . ', ' . $arrAnswer['ID_first_root_comment'] . ', 0, 1, ' . $idFolder . ');return false;';
		  			if (!$arrAnswer['deleted']){
			 		$text .= '<li>
			 				<a attrIdanswerLink="' . $id . '" href="' . $url . '" class="answerLink" onClick="' . $onClick . '">Прокомментировать
			 				</a>
			  			  </li>';
		  			}
			 		if ($branchMinimizeLinkFlag){ // свернуть/развернуть ветку комментариев
			 			if ($branchMinimizeFlag){
			 				$attr = ' minimized="yes" onClick="branchMaximize(this); return false;" ';
			 				$textLink = 'Развернуть ветку';
			 			}
			 			else {
			 				$attr = ' minimized="no"  onClick="branchMinimize(this); return false;" ';
			 				$textLink = 'Cвернуть ветку';
			 			}
			 			$text .= '<li><a href="" class="branchMinimizeLink" attr_id_root="' . $arrAnswer['ID_comment'] . '"' . $attr . ' style="' . ($issetChildren ? NULL : 'display:none;') . '" >' . $textLink . '</a></li>';
			 		}
			  	$text .= '</ul>';

				  		}
				  		elseif(!$arrAnswer['deleted']) {
			 		if ($branchMinimizeLinkFlag){ // свернуть/развернуть ветку комментариев
			 			if ($branchMinimizeFlag){
			 				$attr = ' minimized="yes" onClick="branchMaximize(this); return false;" ';
			 				$textLink = 'Развернуть ветку';
			 			}
			 			else {
			 				$attr = ' minimized="no"  onClick="branchMinimize(this); return false;" ';
			 				$textLink = 'Cвернуть ветку';
			 			}
						$text .= '<ul class="link_comment"><li><a href="" class="branchMinimizeLink" attr_id_root="' . $arrAnswer['ID_comment'] . '"' . $attr . ' style="' . ($issetChildren ? NULL : 'display:none;') . '" >' . $textLink . '</a></li></ul>';
			 		}
		  	}
		  	$text .= '<div id="' . $id . '" attrOpen="no"></div>'; // div для формы ответа
    }
    if ($arrAnswer['ID_answer'] == $idBestAnswer) {
        $text .= '          </div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>';
      }
      else $text .= '</div>';
      if ($return) return $text;
      echo $text;
  }


  public static function displayAnswers($idQuestion, $arrAnswers, $idBestAnswer, $questionAuthorId, $expireStatus, $idFolder = NULL, $noAnswersDiv = false) {
    $objSession = User_Session::instance();
    $sizeArrAnswers = sizeof($arrAnswers);
    $arrTemp = array();
    foreach ($arrAnswers as $arrAnswer)
    	$arrTemp[] = !$arrAnswer['deleted'];
    $answerCount = sizeof(array_filter($arrTemp));

/*    echo '<div class="coments_text_box">
					<!--<span class="svernut_all"><a href="#">Свернуть все, кроме корневых</a></span>-->
					<ul>
						<li>Ответы (<span id="answersAmount">' . $sizeArrAnswers . '</span>)</li>';
						if (!$idBestAnswer && $expireStatus)
						  echo '<li><a href="#leftAnswer" id="linkAddAnswer">Ответить</a></li>';
		echo '</ul>
				</div>';*/
    $isUserAdmin = User_User::checkIfUser('admin', $objSession->getUserId());
//    if (!$idBestAnswer)
//      self::displayLinkToAddAnswer();
		if (!$noAnswersDiv)
   	 echo '<div id="answers">';
//      if (!$idBestAnswer)
//        self::displayAddForm($idQuestion);

      	if (!isset($objComment))
      		$objComment = new Comment();
      	$arrUserInfo = User_User::getUserOfSession();
      	View_Comment::viewComments($objComment->getComments('question', $idQuestion), $idQuestion, 'question', $arrUserInfo, false, false, $expireStatus && !$idBestAnswer, 'Ответить', true, $idFolder, array('idBestAnswer' => $idBestAnswer, 'questionAuthorId' => $questionAuthorId, 'isUserAdmin' => $isUserAdmin, 'answerCount' => $answerCount ));



//        for ($i = 0; $i < $sizeArrAnswers; $i++)
//          self::displayAnswer($arrAnswers[$i], $idBestAnswer, $questionAuthorId, $isUserAdmin, $idFolder);
      if (empty($arrAnswers)) {
        if (!$idBestAnswer) {
          if ($expireStatus)
            echo '<div class="empty" id="noAnswers"><strong>Ответов пока нет. Вы можете быть первым.</strong></div>';
          else
            echo '<div class="empty" id="noAnswers"><strong>Ответов нет.</strong></div>';
        }
      }
	    if (!$noAnswersDiv)
	    	echo '</div>';
//    if (!$idBestAnswer)
//      self::displayAddForm($idQuestion);
  }

  public static function displayLinkToAddAnswer() {
    echo '<div class="answer-addLink">';
      echo '<a href="#" title="" id="linkAddAnswer">!!!Добавить ответ</a>';
    echo '</div>';
  }

  public static function displayAddForm($idQuestion) {
    echo '<div class="ostavut_coment" id="answersAddForm" style="display: block;">';
      echo '<form method="POST">';
        echo '<h3>Ответить</h3><a name="leftAnswer"></a>';
        //echo 'Добавить теги:&nbsp;<input type="text" name="answer[tags]" />';
        //echo '<br />';
        echo '<textarea class="wysiwygComment" style="width: 500px;" name="answer[text]"></textarea>';
        echo '<input type="image" name="submitAddAnswer" src="' . W_IMAGES . 'button/btn_ostavut_comemt.gif" value="Ответить" />
              &nbsp;&nbsp;&nbsp;
              <input type="image" id="hideAnswerField" onclick="return false;" src="' . W_IMAGES . 'button/btn_zakrut.gif" alt="Закрыть" />';

        echo '<input type="hidden" name="answer[idQuestion]" value="' . $idQuestion . '" />';
      echo '</form>';
    echo '</div>';
  }

  /**
   * Выводит список ответов пользователя (вместе с вопросами, на которые он отвечал)
   *
   * @param unknown_type $arrQuestions
   * @return unknown
   */
  public static function showUserAnswers($arrQuestions) {
      if (empty($arrQuestions)) {
        echo '
          <div class="no_essences_notice">
            <p>Пользователь ещё не отвечал на вопросы.</p>
          </div>';
        return false;
      }
      echo '<div class="list_toggling" id="userAnswers">
              <table>
                <tr class="bg_grey">
                  <th></th>
                  <th>Вопрос</th>
                  <th style="width: 35px;"><img style="margin-right: 3px;" alt="" src="' . W_IMAGES . 'icons/img_qwestion_1.gif" height="14" width="16" title="Рейтинг" /></th>
                  <th style="width: 35px;"><img style="margin-right: 3px;" alt="" src="' . W_IMAGES . 'icons/img_qwestion_2.gif" title="Количество ответов" /></th>
                  <th style="width: 60px;"><img style="margin-right: 3px;" alt="" src="' . W_IMAGES . 'icons/img_qwestion_3.gif" title="Осталось до закрытия" /></th>'
                  //<th><img style="margin-right: 3px;" alt="" src="' . W_IMAGES . 'icons/img_qwestion_4.gif" title="Опубликовано" /></th>
                .'</tr>';
        foreach ($arrQuestions as $arrQuestion) {
           echo '<tr idEssence="' . $arrQuestion['ID_question'] . '" essenceType="5">
           		<td class="fist_colum">';
           //<a class="toggle_plus" href="#" onclick="View.ListToggling.toggleContent(this, ' . $arrQuestion['ID_question'] . ', 5); return false;" title="Развернуть вопрос" isDisabled="0"></a>
           //Статус вопроса (до истечения действия)
           if (!is_NULL($arrQuestion['ID_best_answer'])) {
             $classNameStatus = 'time_ok';
             $classTitle = 'Ответ найден';
           }
           else {
             $expireStatus = $arrQuestion['answer_time'] != 5 ? Service_Date::getQuestionExpireStatus($arrQuestion['creation'], $arrQuestion['answer_time']) : 3;
             switch ($expireStatus) {
               case 0: $classNameStatus = 'time_red'; $classTitle = 'Время истекло';break;
               case 1: $classNameStatus = 'time_pred'; $classTitle = 'Время скоро истекает'; break;
               default: case 2: $classNameStatus = 'time'; $classTitle = 'Время ещё есть';break;
               case 3: $classNameStatus = 'time_inf'; $classTitle = 'Ограничения по времени отсутствуют'; break;
             }
           }
           echo '<span class="' . $classNameStatus . '" title="' . $classTitle . '"></span>';
    		   echo '</td>';
           echo '<td>';
             echo View_UniversalInference::getQuestion($arrQuestion, false);
  				 echo '</td>';
           echo '<td><strong>' . round($arrQuestion['total_mark'], 2) . '</strong></td>';
           echo '<td><strong>' . ($arrQuestion['answer_amount'] + $arrQuestion['comment_amount']) . '</strong></td>';
           $expireTime = $arrQuestion['answer_time'] != 5 ? Service_Date::getQuestionExpireTimeLeft($arrQuestion['creation'], $arrQuestion['answer_time']) : '<span class="inf_symbol">&#8734</span>';
           echo '<td><span>' . (($expireTime === false || !is_NULL($arrQuestion['ID_best_answer'])) ? '—' : $expireTime). '</span></td></tr>';
           echo '<tr class="answers">';
             echo '<td></td>';
             echo '<td colspan="4" class="col_answers"><div class="answers">';
                foreach ($arrQuestion['answers'] as $arrAnswer) {
                  self::displayAnswer($arrAnswer, $arrQuestion['ID_best_answer'], $arrQuestion['ID_user'], NULL, NULL, true);
                }
             echo '</div></td>';
           echo '</tr>';
        }
      echo '  </table>';
    echo '</div>';
  }
  
}
?>